package com.example.administrator.hqq.activity.dating;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.layout.EmptyLayout;
import com.example.administrator.hqq.adapter.dating.DatingListAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.dating.DatingListBean;
import com.example.administrator.hqq.bean.event.DatingEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class DatingListActivity extends MyActivity {

    @BindView(R.id.relative)
    RecyclerView relative;
    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.report_auto)
    AutoRelativeLayout reportAuto;
    @BindView(R.id.search)
    TextView search;
    @BindView(R.id.locality)
    RadioButton locality;
    @BindView(R.id.locality_unlimited)
    RadioButton localityUnlimited;
    @BindView(R.id.location_prefer)
    AutoLinearLayout locationPrefer;
    @BindView(R.id.man)
    RadioButton man;
    @BindView(R.id.woman)
    RadioButton woman;
    @BindView(R.id.man_unlimited)
    RadioButton manUnlimited;
    @BindView(R.id.gender_prefer)
    AutoLinearLayout genderPrefer;
    @BindView(R.id.age_young)
    RadioButton ageYoung;
    @BindView(R.id.age_same)
    RadioButton ageSame;
    @BindView(R.id.age_old)
    RadioButton ageOld;
    @BindView(R.id.age_prefer)
    AutoLinearLayout agePrefer;
    @BindView(R.id.search_auto)
    AutoLinearLayout searchAuto;
    @BindView(R.id.issue)
    TextView issue;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.add_dating)
    ImageView addDating;
    @BindView(R.id.confirm)
    Button confirm;
    @BindView(R.id.dating_screen)
    AutoLinearLayout datingScreen;
    @BindView(R.id.empty)
    EmptyLayout empty;
    private String TAG = this.getClass().getSimpleName();
    private int page = 1;
    private List<DatingListBean.DataBean> data;
    private DatingListAdapter datingListAdapter;
    private String last_id = "";
    private String gender_prefer = "0";
    private String city_prefer = "";
    private String age_prefer = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dating_list);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
        initdata();
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    private void initview() {
        title.setText("交友墙");
        search.setVisibility(View.VISIBLE);
        data = new ArrayList<>();
        datingListAdapter = new DatingListAdapter(this, data);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        relative.setLayoutManager(staggeredGridLayoutManager);
        relative.setAdapter(datingListAdapter);
        //设置刷新动画
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(DatingListActivity.this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                page = 1;
                initdata();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initdata();
            }
        });
        datingListAdapter.setDatingListClick(new DatingListAdapter.DatingListClick() {
            @Override
            public void click(int position, ImageView image) {
                if (data.get(position).getType().equals("MINE")) {
                    Intent intent = new Intent(DatingListActivity.this, MineDatingDetailsActivity.class);
                    intent.putExtra(LoongsConfig.dating_id, data.get(position).getId());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(DatingListActivity.this, DatingDetails2Activity.class);
                    intent.putExtra(LoongsConfig.dating_id, data.get(position).getId());
                    intent.putExtra(LoongsConfig.title, data.get(position).getUser_nickname());
                    startActivity(intent);
                }
            }
        });
        //设置预选参数
        gender_prefer = LoongsConfig.getUsersIdSPUtils().getString(LoongsConfig.dating_gender_prefer);
        city_prefer = LoongsConfig.getUsersIdSPUtils().getString(LoongsConfig.dating_city_prefer);
        age_prefer = LoongsConfig.getUsersIdSPUtils().getString(LoongsConfig.dating_age_prefer);
        if (TextUtils.isEmpty(gender_prefer)) {
            if (LoongsConfig.getUsersIdSPUtils().getString(LoongsConfig.gender).equals("MAN")) {
                gender_prefer = "1";
            } else {
                gender_prefer = "2";
            }
        }
        if (TextUtils.isEmpty(city_prefer)) {
            city_prefer = "0";
        }
        if (TextUtils.isEmpty(age_prefer)) {
            age_prefer = "YOUNGER,SAME,OLDER";
        }
    }

    private void initdata() {
        if (page == 1 || data.size() <= 0) {
            last_id = "";
        } else {
            last_id = data.get(data.size() - 1).getId();
        }
        OkHttpUtils.get().url(UrlFactory.datingList()).tag(this)
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.gender_prefer, gender_prefer)
                .addParams(LoongsConfig.city_prefer, city_prefer)
                .addParams(LoongsConfig.age_prefer, age_prefer)
                .addParams(LoongsConfig.key_word, "")
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .addParams(LoongsConfig.last_id, last_id)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "相亲列表onError: " + e.getMessage());
                if (empty!=null)
                    empty.showEmpty();
                if (refreshLayout != null) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (refreshLayout != null) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                Log.e(TAG, "相亲列表onResponse: " + response);
                Gson gson = new Gson();
                DatingListBean datingListBean = gson.fromJson(response, DatingListBean.class);
                if (datingListBean.getCode() == 200) {
                    if (page == 1) {
                        if (datingListBean.getData()==null||datingListBean.getData().size()==0)
                        {
                            empty.showEmpty();
                        }
                        else{
                            empty.hide();
                        }
                        data.clear();
                        data.addAll(datingListBean.getData());
                        datingListAdapter.notifyDataSetChanged();
                    } else {
                        data.addAll(datingListBean.getData());
                        datingListAdapter.notifyItemInserted(data.size());
                    }
                }
            }
        });
    }

    /**
     * 创建帖子的逻辑
     */
    private void addDating() {
        OkHttpUtils.get().url(UrlFactory.prepareAdd()).tag(this)
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "准备发布相亲角onError: " + call);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "准备发布相亲角onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    HintWordsUtils.showMarkeWords(code, jsonObject.getString(LoongsConfig.description));
                    String datingId = jsonObject.getString(LoongsConfig.dating_id);
                    if (code == 200) {
                        CreatDatingActivity.start(DatingListActivity.this, datingId, CreatDatingActivity.Type.CREAT);
                    } else if (code == 201) {
                        Intent intent = new Intent(DatingListActivity.this, MineDatingDetailsActivity.class);
                        intent.putExtra(LoongsConfig.dating_id, datingId);
                        startActivity(intent);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.return_auto, R.id.search, R.id.search_auto, R.id.dating_screen, R.id.add_dating, R.id.locality, R.id.locality_unlimited, R.id.man, R.id.woman, R.id.man_unlimited, R.id.age_old, R.id.age_young, R.id.age_same, R.id.confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_auto:
                finish();
                break;
            case R.id.search:
                searchAuto.setVisibility(View.VISIBLE);
                showSearchAuto();
                break;
            case R.id.search_auto:
                searchAuto.setVisibility(View.GONE);
                dismissSearchAuto();
                break;
            case R.id.dating_screen:
                break;
            case R.id.add_dating:
                addDating();
                break;
        }
        setDatingScreenClicked(view);
    }

    /**
     * 设置筛选项的点击事件
     *
     * @param view
     */
    private void setDatingScreenClicked(View view) {
        switch (view.getId()) {
            case R.id.locality:
                city_prefer = "1";
                setBlackTextColor(localityUnlimited);
                setGreenTextColor(locality);
                break;
            case R.id.locality_unlimited:
                city_prefer = "0";
                setBlackTextColor(locality);
                setGreenTextColor(localityUnlimited);
                break;
            case R.id.man:
                gender_prefer = "1";
                setGreenTextColor(man);
                setBlackTextColor(woman);
                setBlackTextColor(manUnlimited);
                break;
            case R.id.woman:
                gender_prefer = "2";
                setGreenTextColor(woman);
                setBlackTextColor(man);
                setBlackTextColor(manUnlimited);
                break;
            case R.id.man_unlimited:
                gender_prefer = "0";
                setGreenTextColor(manUnlimited);
                setBlackTextColor(man);
                setBlackTextColor(woman);
                break;
            case R.id.age_young:
                setSelectedAge(ageYoung);
                break;
            case R.id.age_same:
                setSelectedAge(ageSame);
                break;
            case R.id.age_old:
                setSelectedAge(ageOld);
                break;
            case R.id.confirm:
                searchAuto.setVisibility(View.GONE);
                dismissSearchAuto();
                initdata();
                break;
        }
    }

    /**
     * 设置筛选隐藏时候报保存选择的条件
     */
    private void dismissSearchAuto() {
        SPUtils usersIdSPUtils = LoongsConfig.getUsersIdSPUtils();
        usersIdSPUtils.put(LoongsConfig.dating_gender_prefer, gender_prefer);
        usersIdSPUtils.put(LoongsConfig.dating_city_prefer, city_prefer);
        ArrayList<String> strings = new ArrayList<>();
        ageStatic();
    }

    /**
     * 获取age_prefer的状态值
     */
    private void ageStatic() {
        ArrayList<String> strings = new ArrayList<>();
        if (ageYoung.isSelected()) {
            strings.add("YOUNGER");
        }
        if (ageSame.isSelected()) {
            strings.add("SAME");
        }
        if (ageOld.isSelected()) {
            strings.add("OLDER");
        }
        if (strings.size() == 0) {
            age_prefer = "YOUNGER,SAME,OLDER";
        } else {
            for (int i = 0; i < strings.size(); i++) {
                if (i == 0) {
                    age_prefer = strings.get(i);
                } else {
                    age_prefer += "," + strings.get(i);
                }
            }
        }
        LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.dating_age_prefer, age_prefer);
    }

    /**
     * 设置筛选显示时条件的状态
     */
    private void showSearchAuto() {
        String[] split = age_prefer.split(",");
        for (String s : split) {
            if (s.equals("YOUNGER")) {
                ageYoung.setSelected(false);
                setSelectedAge(ageYoung);
            } else if (s.equals("SAME")) {
                ageSame.setSelected(false);
                setSelectedAge(ageSame);
            } else {
                ageOld.setSelected(false);
                setSelectedAge(ageOld);
            }
        }
        switch (gender_prefer) {
            case "0":
                setGreenTextColor(manUnlimited);
                setBlackTextColor(man);
                setBlackTextColor(woman);
                break;
            case "1":
                setGreenTextColor(man);
                setBlackTextColor(woman);
                setBlackTextColor(manUnlimited);
                break;
            case "2":
                setGreenTextColor(woman);
                setBlackTextColor(man);
                setBlackTextColor(manUnlimited);
                break;
        }
        if (city_prefer.equals("1")) {
            setBlackTextColor(localityUnlimited);
            setGreenTextColor(locality);
        } else {
            setBlackTextColor(locality);
            setGreenTextColor(localityUnlimited);
        }
    }

    /**
     * 设置年龄限制
     *
     * @param radioButton
     */
    private void setSelectedAge(RadioButton radioButton) {
        radioButton.setSelected(!radioButton.isSelected());
        if (radioButton.isSelected()) {
            setGreenTextColor(radioButton);
        } else {
            setBlackTextColor(radioButton);
        }
        ageStatic();
    }

    private void setGreenTextColor(RadioButton radioButton) {
        radioButton.setTextColor(Color.parseColor("#00AE9D"));
    }

    private void setBlackTextColor(RadioButton radioButton) {
        radioButton.setTextColor(Color.parseColor("#000000"));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(DatingEvent datingEvent) {
        switch (datingEvent.getDatingType()) {
            case REFRESH:
                page = 1;
                initdata();
                break;
            case CREAD:
                page = 1;
                initdata();
                break;
            case DELETE:
                for (DatingListBean.DataBean datum : data) {
                    if (datum.getId().equals(datingEvent.getDating_id())) {
                        data.remove(datum);
                        datingListAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                break;
            case COMPILE:
                initdata();
                break;
        }

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}